package array;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 对角线：在同一对角线上的元素，其横纵坐标之差相等
 */
public class DiagonalSort {

    public int[][] diagonalSort(int[][] matrix) {
        int m = matrix.length, n = matrix[0].length;

        // 存储所有对角线的元素列表
        Map<Integer, ArrayList<Integer>> diagonals = new HashMap<>();

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                // 横纵坐标之差可以作为一条对角线的ID
                int diagonalID = i - j;
                diagonals.putIfAbsent(diagonalID, new ArrayList<>());
                diagonals.get(diagonalID).add(matrix[i][j]);
            }
        }

        // 从数组尾部删除元素效率较高，所以把ArrayList倒序排序
        for (ArrayList<Integer> value : diagonals.values()) {
            Collections.sort(value, Collections.reverseOrder());
        }

        // 把排序结果填充回原矩阵
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                ArrayList<Integer> diagonal = diagonals.get(i - j);
                matrix[i][j] = diagonal.remove(diagonal.size() - 1);
            }
        }

        return matrix;
    }
}
